<?php

namespace App\Http\Controllers\Api;

use App\Models\MemberAddress;
use App\Models\MemberLabel;
use App\Repositories\AddressRepository;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\SupplierRepository;
use App\Repositories\Api\WechatMenusRepository;
use App\Repositories\FileRepository;
use App\Repositories\PictureMappingRepository;
use App\Repositories\WechatRepository;


class MemberController extends MiniAppController
{
    /**
     * @var
     */
    private $memberRep,
        $wechatRep,
        $wechatMenusRep;

    public function __construct(
        MemberRepository      $memberRep,
        WechatMenusRepository $wechatMenusRep,
        WechatRepository      $wechatRep
    )
    {
        parent::__construct();
        $this->memberRep = $memberRep;
        $this->wechatRep = $wechatRep;
        $this->wechatMenusRep = $wechatMenusRep;
    }

    public function detail()
    {
        $params = request()->only("id", "wechat_admin_id");
        $adminId = intval($params['id']) ? intval($params['id']) : $params['wechat_admin_id'];
        if ($adminId != UID)
            return $this->apiResponse->error("没访问权限", 400);

        $admin = $this->memberRep->getAdminInfo($adminId);
        $tags = $this->memberRep->getTypes(UID);
        if (in_array(2, $tags)) { //职工
            $admin['type'] = 2;
        } else {
            $admin['type'] = 1;
        }
        return retSuc($admin ?? []);
//        return $this->apiResponse->success($admin ?? []);
    }

    /**
     * 上传文件
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-17T18:05:32+0800
     * @return   [type]                   [description]
     */
    public function upload()
    {
        $field_key = request()->get("field_key");
        $fileData = request()->file('fileData');
        $file_type = "member";
        $res = app(FileRepository::class)->upload($fileData, $file_type);
        $res['size'] = formatBytes($res['size']);
        $res['full_path'] = getPreviewImage($res['full_path']);

        //生活照
        if ($field_key == 'pictures') {
            $res['picture_id'] = (new PictureMappingRepository())->savePic(UID, "member", $res['id']);
        } else if ($field_key == 'avatar') {//头像
            $this->memberRep->updateFields(UID, ['avatar' => $res['path']]);
        } else if ($field_key == 'weixin_qrcode_pic') {//保存微信二维码
            $this->memberRep->updateFields(UID, ['weixin_qrcode_pic' => $res['path']]);
        }

        return retSuc($res);
    }

    /**
     * 恢复账户
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-30T10:16:04+0800
     * @return   [type]                   [description]
     */
    public function recover()
    {
        $this->memberRep->updateFields(request()->get("wechat_admin_id"), ['cancel' => 1]);
        return $this->apiResponse->success([], '恢复成功');
    }

    public function address_list()
    {
//        $user_type = Member::query()->where("id", "=", UID)->value("type");
        $tags = $this->memberRep->getTypes(UID);
        if (in_array(2, $tags)) { //职工
            $user_type = 2;
        } else {//病患
            $user_type = 1;
        }
        $res = (new AddressRepository())->getAreas([], $user_type);
        return retSuc(['addressList' => $res]);
    }

    /**
     * 我的地址
     */
    public function address_my()
    {
        $original = request()->get("original"); //非从选择地址来
        $filter['uid'] = UID;
        if ($original != 'my') {
            $tags = $this->memberRep->getTypes(UID);
            if (in_array(2, $tags)) { //职工
                $filter['type'] = 2;
            } else {
                $filter['type'] = 1;
            }
        }

        $res = (new AddressRepository())->getMyAddress($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function edit_address()
    {
        $params = request()->all();
        if (empty($params['consignee'])) {
            return retFail("联系人必填");
        }
        if (empty($params['phone'])) {
            return retFail("手机号必填");
        }
        if (empty($params['province_id'])) {
            return retFail("楼栋必填");
        }
        if (empty($params['city_id'])) {
            return retFail("楼层必填");
        }
        if (empty($params['region_id'])) {
            return retFail("科室必填");
        }

        if (!$params['id']) {
            $tags = $this->memberRep->getTypes(UID);

            if (in_array(2, $tags)) { //职工
                $params['type'] = 2;
            }
        }

        $last_id = (new AddressRepository())->saveOrUpdate($params['id'] ?? 0, $params);

        return retSuc(['id' => $last_id]);
    }

    /**
     * 地址详情
     */
    public function address()
    {
        $id = intval(request()->get("id"));
        if (!empty($id)) {
            $filter['id'] = $id;
        } else {
//            $filter['is_default'] = 1;
        }
        $tags = $this->memberRep->getTypes(UID);
        if (in_array(2, $tags)) { //职工
            $filter['type'] = 2;
        } else {
            $filter['type'] = 1;
        }

        $res = (new AddressRepository())->getAddressInfo($id, UID, $filter);
        $member = $this->memberRep->getOne(UID);

        return retSuc(['address' => $res, 'member' => $member]);
    }

    /**
     * 设置默认值
     */
    public function address_set_default()
    {
        $id = intval(request()->post("id"));
        if (empty($id))
            return retFail("参数错误");

        return (new AddressRepository())->setDefault($id, UID);
    }

    /**
     * 更新字段
     * @Author   thomashtao               bosslen
     * @DateTime 2022-03-29T16:02:32+0800
     * @return   [type]                   [description]
     */
    public function update_field()
    {
        $field_key = request()->post("field_key");
        if (empty($field_key)) {
            return retFail("参数错误");
        }

        if ($field_key && in_array($field_key, ['type', 'username'])) {
            $type = request()->post($field_key);

            if (!empty($data['field_key'])) {
                unset($data['field_key']);
            }
            $m_data[$field_key] = $type;
            $this->memberRep->saveOrUpdate($m_data, UID);
        }

        return retSuc([], "更新成功");
    }

    /**
     * 我的数据
     */
    public function init()
    {
        $res = $this->memberRep->getOne(UID);

        $address_amount = MemberAddress::query()->where(['uid' => UID])->count("id");
        $kefu_mobile = C("kefu_mobile");

        return retSuc([
            'member' => $res,
            'mobile' => $kefu_mobile,
            'address_amount' => $address_amount
        ]);
    }

    /**
     * 配送人员初始化数据
     */
    public function deliver_init()
    {
        $params = request()->all();
        $member = $this->memberRep->getSimpleMember(UID);

        $statusList = order_deliver_status();
        $suppliers = (new SupplierRepository())->getSupplierMenus($params);
        $areaList = (new  AddressRepository())->getAreas([], 2);
        $deliver_timeList = getDeliveryTimes();

        return retSuc(compact("suppliers", "statusList", "areaList", 'member', 'deliver_timeList'));
    }

    /**
     * 删除地址
     */
    public function del_address()
    {
        $address_id = intval(request()->post("id", 0));
        if (!$address_id)
            return retFail("参数错误");

        return $this->memberRep->deleteAddress($address_id, UID);
    }

    /**
     * 更新标签
     */
    public function update_tag()
    {
        $tagId = intval(request()->post("tagId", 0));

        $tags = member_tag();
        if (!$tagId || !$tags[$tagId]) {
            return retFail("标签不存在");
        }

        if (MemberLabel::where(['uid' => UID])->whereIn("type", [1, 2, 5, 6])->count("id")) {
            return retSuc(['tags' => $this->memberRep->getTypes(UID)]);
        }

        MemberLabel::create([
            "uid" => UID,
            "type" => $tagId,
        ]);

        return retSuc(['tags' => $this->memberRep->getTypes(UID)]);
    }

    /**
     * 更新园区
     */
    public function update_park()
    {
        return retSuc();
    }

}